<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="flex items-center gap-6">
				<div class="flex items-center gap-2">
					<img id="img-head" src="img/jstu1.webp">
					<span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
				</div>
				<div class="flex items-center gap-2">
					<a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
				</div>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }">
				<span class="iconify" data-icon="mdi:view-dashboard"></span>
				<a @click="$router.push('/admin')">系统管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
				<span class="iconify" data-icon="mdi:account-group"></span>
				<a @click="$router.push('/admin/users')">用户管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
				<span class="iconify" data-icon="mdi:clipboard-list"></span>
				<a @click="$router.push('/admin/projects')">项目管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
				<span class="iconify" data-icon="mdi:calendar-clock"></span>
				<a @click="$router.push('/admin/schedule')">赛程管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/judges' }">
				<span class="iconify" data-icon="mdi:whistle"></span>
				<a @click="$router.push('/admin/judges')">裁判分配</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/system-config' }">
				<span class="iconify" data-icon="mdi:cog"></span>
				<a @click="$router.push('/admin/system-config')">系统配置</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/dict-type' }">
				<span class="iconify" data-icon="mdi:book-open"></span>
				<a @click="$router.push('/admin/dict-type')">字典管理</a>
			</div>
			<div class="menu-item active">
				<span class="iconify" data-icon="mdi:format-list-bulleted"></span>
				字典数据
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<div class="main-content-header">
				<h1 class="text-2xl font-medium">字典数据管理</h1>
				<div class="header-actions">
					<el-button type="warning" size="small" @click="handleRefreshCache">
						<i class="el-icon-refresh"></i> 刷新缓存
					</el-button>
					<el-button type="success" size="small" @click="handleExportDictData">
						<i class="el-icon-download"></i> 导出数据
					</el-button>
					<el-button type="info" size="small" @click="handleImportDictData">
						<i class="el-icon-upload2"></i> 导入数据
					</el-button>
					<el-button type="primary" size="small" @click="handleAdd">
						<i class="el-icon-plus"></i> 添加字典数据
					</el-button>
				</div>
			</div>

			<!-- 搜索区域 -->
			<div class="search-bar">
				<el-form :inline="true" :model="searchForm" size="small">
					<el-form-item label="字典类型">
						<el-select v-model="searchForm.dictTypeId" placeholder="请选择字典类型" clearable style="width: 200px">
							<el-option
								v-for="dictType in dictTypeOptions"
								:key="dictType.id"
								:label="dictType.dictName"
								:value="dictType.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="字典标签">
						<el-input v-model="searchForm.dictLabel" placeholder="请输入字典标签" clearable style="width: 200px"></el-input>
					</el-form-item>
					<el-form-item label="字典值">
						<el-input v-model="searchForm.dictValue" placeholder="请输入字典值" clearable style="width: 200px"></el-input>
					</el-form-item>
					<el-form-item label="状态">
						<el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
							<el-option label="启用" :value="1"></el-option>
							<el-option label="停用" :value="0"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch" :loading="loading">
							<i class="el-icon-search"></i> 搜索
						</el-button>
						<el-button @click="handleReset">
							<i class="el-icon-refresh"></i> 重置
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 字典数据表格 -->
			<div class="table-container">
				<el-table
					:data="tableData"
					v-loading="loading"
					stripe
					border
					style="width: 100%"
					@selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column prop="id" label="数据ID" width="80" align="center"></el-table-column>
					<el-table-column prop="dictTypeName" label="字典类型" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="dictLabel" label="字典标签" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="dictValue" label="字典值" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="dictSort" label="排序" width="80" align="center"></el-table-column>
					<el-table-column prop="cssClass" label="样式属性" width="120" align="center"></el-table-column>
					<el-table-column prop="listClass" label="表格回显样式" width="120" align="center"></el-table-column>
					<el-table-column prop="isDefault" label="默认值" width="80" align="center">
						<template #default="scope">
							<el-tag :type="scope.row.isDefault === 1 ? 'success' : 'info'" size="small">
								{{ scope.row.isDefault === 1 ? '是' : '否' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="status" label="状态" width="80" align="center">
						<template #default="scope">
							<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
								{{ scope.row.status === 1 ? '启用' : '停用' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="180" align="center">
						<template #default="scope">
							{{ formatDateTime(scope.row.createdAt) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="240" align="center" fixed="right">
						<template #default="scope">
							<el-button-group size="mini">
								<el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
								<el-button type="info" icon="el-icon-top" @click="handleMoveUp(scope.row)" :disabled="scope.row.dictSort === 0">上移</el-button>
								<el-button type="info" icon="el-icon-bottom" @click="handleMoveDown(scope.row)">下移</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pagination.currentPage"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pagination.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pagination.total">
					</el-pagination>
				</div>

				<!-- 批量操作 -->
				<div class="batch-operations" v-if="selectedDictData.length > 0">
					<span>已选择 {{ selectedDictData.length }} 项</span>
					<el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
					<el-button type="warning" size="small" @click="handleBatchDisable">批量停用</el-button>
					<el-button type="success" size="small" @click="handleBatchEnable">批量启用</el-button>
				</div>
			</div>

			<!-- 字典数据编辑对话框 -->
			<el-dialog
				:title="dialogTitle"
				v-model="dialogVisible"
				width="600px"
				:before-close="handleDialogClose">
				<el-form :model="dictDataForm" :rules="dictDataFormRules" ref="dictDataFormRef" label-width="100px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="字典类型" prop="dictTypeId">
								<el-select v-model="dictDataForm.dictTypeId" placeholder="请选择字典类型" style="width: 100%">
									<el-option
										v-for="dictType in dictTypeOptions"
										:key="dictType.id"
										:label="dictType.dictName"
										:value="dictType.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="排序" prop="dictSort">
								<el-input-number v-model="dictDataForm.dictSort" :min="0" :max="999" style="width: 100%"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="字典标签" prop="dictLabel">
								<el-input v-model="dictDataForm.dictLabel" placeholder="请输入字典标签"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="字典值" prop="dictValue">
								<el-input v-model="dictDataForm.dictValue" placeholder="请输入字典值"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="样式属性" prop="cssClass">
								<el-input v-model="dictDataForm.cssClass" placeholder="请输入样式属性"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="表格回显样式" prop="listClass">
								<el-select v-model="dictDataForm.listClass" placeholder="请选择表格回显样式" style="width: 100%" clearable>
									<el-option label="默认" value=""></el-option>
									<el-option label="成功" value="success"></el-option>
									<el-option label="信息" value="info"></el-option>
									<el-option label="警告" value="warning"></el-option>
									<el-option label="危险" value="danger"></el-option>
									<el-option label="主要" value="primary"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="默认值" prop="isDefault">
								<el-switch
									v-model="dictDataForm.isDefault"
									:active-value="1"
									:inactive-value="0"
									active-text="是"
									inactive-text="否">
								</el-switch>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="状态" prop="status">
								<el-switch
									v-model="dictDataForm.status"
									:active-value="1"
									:inactive-value="0"
									active-text="启用"
									inactive-text="停用">
								</el-switch>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="备注" prop="remark">
						<el-input
							v-model="dictDataForm.remark"
							type="textarea"
							:rows="3"
							placeholder="请输入备注"></el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleDialogClose">取消</el-button>
						<el-button type="primary" @click="handleSave" :loading="saveLoading">确定</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 字典数据导入对话框 -->
			<el-dialog
				title="字典数据导入"
				v-model="importDialogVisible"
				width="600px"
				:before-close="handleImportDialogClose">
				<el-steps :active="importStep" finish-status="success" simple style="margin-bottom: 20px;">
					<el-step title="选择文件" icon="el-icon-upload"></el-step>
					<el-step title="数据预览" icon="el-icon-view"></el-step>
					<el-step title="导入确认" icon="el-icon-check"></el-step>
				</el-steps>

				<!-- 步骤1：选择文件 -->
				<div v-show="importStep === 0">
					<el-upload
						ref="uploadRef"
						:action="''"
						:auto-upload="false"
						:on-change="handleImportFileChange"
						:limit="1"
						accept=".xlsx,.xls,.json"
						drag>
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						<template #tip>
							<div class="el-upload__tip">
								支持Excel(.xlsx/.xls)和JSON格式文件，文件大小不超过10MB
							</div>
						</template>
					</el-upload>

					<div class="import-tips">
						<el-alert
							title="导入说明"
							type="info"
							:closable="false"
							show-icon>
							<template #default>
								<p>1. Excel文件格式：第一行为表头(字典类型、字典标签、字典值、排序、样式属性、表格回显样式、默认值、状态、备注)</p>
								<p>2. JSON文件格式：请参考模板格式</p>
								<p>3. 字典数据已存在的将更新，不存在的将新增</p>
							</template>
						</el-alert>
					</div>

					<div class="template-download">
						<el-button type="text" @click="downloadTemplate">
							<i class="el-icon-download"></i> 下载导入模板
						</el-button>
					</div>
				</div>

				<!-- 步骤2：数据预览 -->
				<div v-show="importStep === 1">
					<el-table :data="importPreviewData" border max-height="400" style="width: 100%">
						<el-table-column prop="dictTypeName" label="字典类型" width="150"></el-table-column>
						<el-table-column prop="dictLabel" label="字典标签" width="120"></el-table-column>
						<el-table-column prop="dictValue" label="字典值" width="120"></el-table-column>
						<el-table-column prop="dictSort" label="排序" width="80"></el-table-column>
						<el-table-column prop="cssClass" label="样式属性" width="120"></el-table-column>
						<el-table-column prop="listClass" label="表格回显样式" width="120"></el-table-column>
						<el-table-column prop="isDefault" label="默认值" width="80">
							<template #default="scope">
								{{ scope.row.isDefault === 1 ? '是' : '否' }}
							</template>
						</el-table-column>
						<el-table-column prop="status" label="状态" width="80">
							<template #default="scope">
								{{ scope.row.status === 1 ? '启用' : '停用' }}
							</template>
						</el-table-column>
						<el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
						<el-table-column prop="status" label="导入状态" width="100">
							<template #default="scope">
								<el-tag v-if="scope.row.importStatus === 'new'" type="success">新增</el-tag>
								<el-tag v-else-if="scope.row.importStatus === 'update'" type="warning">更新</el-tag>
								<el-tag v-else type="danger">错误</el-tag>
							</template>
						</el-table-column>
					</el-table>

					<div class="import-summary">
						<el-alert
							:title="`共解析到 ${importPreviewData.length} 条数据，其中 ${getImportSummary().newCount} 条新增，${getImportSummary().updateCount} 条更新，${getImportSummary().errorCount} 条错误`"
							:type="getImportSummary().errorCount > 0 ? 'warning' : 'success'"
							:closable="false"
							show-icon>
						</el-alert>
					</div>
				</div>

				<!-- 步骤3：导入确认 -->
				<div v-show="importStep === 2">
					<el-result
						icon="success"
						title="数据验证完成"
						:sub-title="`确认要导入 ${getImportSummary().validCount} 条有效数据吗？`">
					</el-result>
				</div>

				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleImportDialogClose">取消</el-button>
						<el-button v-if="importStep > 0" @click="importStep--">上一步</el-button>
						<el-button
							v-if="importStep < 2"
							type="primary"
							@click="handleNextStep"
							:disabled="importStep === 0 && !importFile">
							下一步
						</el-button>
						<el-button
							v-if="importStep === 2"
							type="primary"
							@click="handleConfirmImport"
							:loading="importLoading">
							确认导入
						</el-button>
					</div>
				</template>
			</el-dialog>
		</main>
	</div>
</template>

<script>
import {
	getDictDataPage,
	addDictData,
	updateDictData,
	deleteDictData,
	batchDeleteDictData,
	updateDictDataStatus,
	refreshDictDataCache,
	checkDictValueExists,
	batchUpdateDictSort
} from '@/api/dict-data'
import { getAllEnabledDictTypes } from '@/api/dict-type'
import { useAuthStore } from '@/stores/auth'

export default {
	name: 'DictData',
	setup() {
		const authStore = useAuthStore()
		return {
			authStore
		}
	},
	data() {
		return {
			// 当前用户信息
			currentUser: null,

			// 搜索表单
			searchForm: {
				dictTypeId: null,
				dictLabel: '',
				dictValue: '',
				status: null
			},

			// 字典类型选项
			dictTypeOptions: [],

			// 表格数据
			tableData: [],
			loading: false,

			// 分页信息
			pagination: {
				currentPage: 1,
				pageSize: 10,
				total: 0
			},

			// 选中的字典数据
			selectedDictData: [],

			// 对话框相关
			dialogVisible: false,
			dialogTitle: '添加字典数据',
			isEdit: false,
			saveLoading: false,

			// 字典数据表单
			dictDataForm: {
				id: null,
				dictTypeId: null,
				dictLabel: '',
				dictValue: '',
				dictSort: 0,
				cssClass: '',
				listClass: '',
				isDefault: 0,
				status: 1,
				remark: ''
			},

			// 表单验证规则
			dictDataFormRules: {
				dictTypeId: [
					{ required: true, message: '请选择字典类型', trigger: 'change' }
				],
				dictLabel: [
					{ required: true, message: '请输入字典标签', trigger: 'blur' },
					{ min: 1, max: 100, message: '字典标签长度在 1 到 100 个字符', trigger: 'blur' }
				],
				dictValue: [
					{ required: true, message: '请输入字典值', trigger: 'blur' },
					{ min: 1, max: 100, message: '字典值长度在 1 到 100 个字符', trigger: 'blur' }
				]
			},

			// 字典数据导入相关
			importDialogVisible: false,
			importStep: 0,
			importFile: null,
			importPreviewData: [],
			importLoading: false
		}
	},

	created() {
		// 获取当前用户信息
		this.currentUser = this.authStore.userInfo || JSON.parse(localStorage.getItem('userInfo'))
		// 加载字典类型选项
		this.loadDictTypeOptions()
		// 加载数据
		this.loadData()
	},

	methods: {
		// 加载字典类型选项
		async loadDictTypeOptions() {
			try {
				const response = await getAllEnabledDictTypes()
				if (response.code === 200) {
					this.dictTypeOptions = response.data
				} else {
					this.$message.error(response.message || '获取字典类型失败')
				}
			} catch (error) {
				console.error('获取字典类型失败:', error)
				this.$message.error('获取字典类型失败')
			}
		},

		// 加载数据
		async loadData() {
			this.loading = true
			try {
				const params = {
					...this.searchForm,
					currentPage: this.pagination.currentPage,
					pageSize: this.pagination.pageSize
				}

				const response = await getDictDataPage(this.pagination.currentPage, this.pagination.pageSize, params)

				if (response.code === 200) {
					this.tableData = response.data.records.map(item => ({
						...item,
						status: parseInt(item.status),
						isDefault: parseInt(item.isDefault)
					}))
					this.pagination.total = response.data.total
				} else {
					this.$message.error(response.message || '获取数据失败')
				}
			} catch (error) {
				console.error('获取字典数据失败:', error)
				this.$message.error('获取数据失败')
			} finally {
				this.loading = false
			}
		},

		// 搜索
		handleSearch() {
			this.pagination.currentPage = 1
			this.loadData()
		},

		// 重置搜索
		handleReset() {
			this.searchForm = {
				dictTypeId: null,
				dictLabel: '',
				dictValue: '',
				status: null
			}
			this.handleSearch()
		},

		// 分页大小改变
		handleSizeChange(val) {
			this.pagination.pageSize = val
			this.loadData()
		},

		// 当前页改变
		handleCurrentChange(val) {
			this.pagination.currentPage = val
			this.loadData()
		},

		// 表格选择改变
		handleSelectionChange(selection) {
			this.selectedDictData = selection
		},

		// 添加字典数据
		handleAdd() {
			this.dialogTitle = '添加字典数据'
			this.isEdit = false
			this.dictDataForm = {
				id: null,
				dictTypeId: null,
				dictLabel: '',
				dictValue: '',
				dictSort: 0,
				cssClass: '',
				listClass: '',
				isDefault: 0,
				status: 1,
				remark: ''
			}
			this.dialogVisible = true
		},

		// 编辑字典数据
		handleEdit(row) {
			this.dialogTitle = '编辑字典数据'
			this.isEdit = true
			this.dictDataForm = {
				...row,
				status: parseInt(row.status),
				isDefault: parseInt(row.isDefault)
			}
			this.dialogVisible = true
		},

		// 保存字典数据
		async handleSave() {
			this.$refs.dictDataFormRef.validate(async (valid) => {
				if (valid) {
					this.saveLoading = true
					try {
						let response
						if (this.isEdit) {
							response = await updateDictData(this.dictDataForm)
						} else {
							// 检查字典值是否已存在
							const checkResponse = await checkDictValueExists(this.dictDataForm.dictTypeId, this.dictDataForm.dictValue)
							if (checkResponse.code === 200 && checkResponse.data) {
								this.$message.error('字典值已存在')
								this.saveLoading = false
								return
							}
							response = await addDictData(this.dictDataForm)
						}

						if (response.code === 200) {
							this.$message.success(this.isEdit ? '更新成功' : '添加成功')
							this.dialogVisible = false
							this.loadData()
						} else {
							this.$message.error(response.message || (this.isEdit ? '更新失败' : '添加失败'))
						}
					} catch (error) {
						console.error('保存字典数据失败:', error)
						this.$message.error(this.isEdit ? '更新失败' : '添加失败')
					} finally {
						this.saveLoading = false
					}
				}
			})
		},

		// 删除字典数据
		handleDelete(row) {
			this.$confirm('确定要删除该字典数据吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await deleteDictData(row.id)
					if (response.code === 200) {
						this.$message.success('删除成功')
						this.loadData()
					} else {
						this.$message.error(response.message || '删除失败')
					}
				} catch (error) {
					console.error('删除字典数据失败:', error)
					this.$message.error('删除失败')
				}
			})
		},

		// 批量删除
		handleBatchDelete() {
			this.$confirm(`确定要删除选中的 ${this.selectedDictData.length} 个字典数据吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const dictDataIds = this.selectedDictData.map(dictData => dictData.id)
					const response = await batchDeleteDictData(dictDataIds)
					if (response.code === 200) {
						this.$message.success('批量删除成功')
						this.loadData()
						this.selectedDictData = []
					} else {
						this.$message.error(response.message || '批量删除失败')
					}
				} catch (error) {
					console.error('批量删除失败:', error)
					this.$message.error('批量删除失败')
				}
			})
		},

		// 切换字典数据状态
		async handleToggleStatus(row) {
			const action = row.status === 1 ? '停用' : '启用'
			this.$confirm(`确定要${action}该字典数据吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const response = await updateDictDataStatus(row.id, row.status === 1 ? 0 : 1)
					if (response.code === 200) {
						this.$message.success(`${action}成功`)
						this.loadData()
					} else {
						this.$message.error(response.message || `${action}失败`)
					}
				} catch (error) {
					console.error(`${action}字典数据失败:`, error)
					this.$message.error(`${action}失败`)
				}
			})
		},

		// 批量启用
		handleBatchEnable() {
			this.$confirm(`确定要启用选中的 ${this.selectedDictData.length} 个字典数据吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const dictDataIds = this.selectedDictData.map(dictData => dictData.id)
					const promises = dictDataIds.map(id => updateDictDataStatus(id, 1))
					await Promise.all(promises)
					this.$message.success('批量启用成功')
					this.loadData()
					this.selectedDictData = []
				} catch (error) {
					console.error('批量启用失败:', error)
					this.$message.error('批量启用失败')
				}
			})
		},

		// 批量停用
		handleBatchDisable() {
			this.$confirm(`确定要停用选中的 ${this.selectedDictData.length} 个字典数据吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					const dictDataIds = this.selectedDictData.map(dictData => dictData.id)
					const promises = dictDataIds.map(id => updateDictDataStatus(id, 0))
					await Promise.all(promises)
					this.$message.success('批量停用成功')
					this.loadData()
					this.selectedDictData = []
				} catch (error) {
					console.error('批量停用失败:', error)
					this.$message.error('批量停用失败')
				}
			})
		},

		// 上移字典数据
		async handleMoveUp(row) {
			if (row.dictSort <= 0) {
				this.$message.warning('已经是第一项了')
				return
			}

			try {
				// 找到同类型的上一个数据
				const prevData = this.tableData.find(item =>
					item.dictTypeId === row.dictTypeId &&
					item.dictSort === row.dictSort - 1
				)

				if (prevData) {
					const sortMap = {
						[row.id]: row.dictSort - 1,
						[prevData.id]: prevData.dictSort + 1
					}

					const response = await batchUpdateDictSort(sortMap)
					if (response.code === 200) {
						this.$message.success('上移成功')
						this.loadData()
					} else {
						this.$message.error(response.message || '上移失败')
					}
				} else {
					// 如果没有找到上一个数据，直接将当前数据的排序减1
					const sortMap = {
						[row.id]: row.dictSort - 1
					}

					const response = await batchUpdateDictSort(sortMap)
					if (response.code === 200) {
						this.$message.success('上移成功')
						this.loadData()
					} else {
						this.$message.error(response.message || '上移失败')
					}
				}
			} catch (error) {
				console.error('上移失败:', error)
				this.$message.error('上移失败')
			}
		},

		// 下移字典数据
		async handleMoveDown(row) {
			try {
				// 找到同类型的下一个数据
				const nextData = this.tableData.find(item =>
					item.dictTypeId === row.dictTypeId &&
					item.dictSort === row.dictSort + 1
				)

				if (nextData) {
					const sortMap = {
						[row.id]: row.dictSort + 1,
						[nextData.id]: nextData.dictSort - 1
					}

					const response = await batchUpdateDictSort(sortMap)
					if (response.code === 200) {
						this.$message.success('下移成功')
						this.loadData()
					} else {
						this.$message.error(response.message || '下移失败')
					}
				} else {
					// 如果没有找到下一个数据，直接将当前数据的排序加1
					const sortMap = {
						[row.id]: row.dictSort + 1
					}

					const response = await batchUpdateDictSort(sortMap)
					if (response.code === 200) {
						this.$message.success('下移成功')
						this.loadData()
					} else {
						this.$message.error(response.message || '下移失败')
					}
				}
			} catch (error) {
				console.error('下移失败:', error)
				this.$message.error('下移失败')
			}
		},

		// 刷新缓存
		async handleRefreshCache() {
			try {
				const response = await refreshDictDataCache()
				if (response.code === 200) {
					this.$message.success('缓存刷新成功')
				} else {
					this.$message.error(response.message || '缓存刷新失败')
				}
			} catch (error) {
				console.error('刷新缓存失败:', error)
				this.$message.error('刷新缓存失败')
			}
		},

		// 关闭对话框
		handleDialogClose() {
			this.dialogVisible = false
			this.$refs.dictDataFormRef.resetFields()
		},

		// 退出登录
		async handleLogout() {
			this.$confirm('确定要退出登录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				// 使用Pinia store进行登出
				await this.authStore.logout()
				// 跳转到登录页
				this.$router.push('/login')
			})
		},

		// 格式化日期时间
		formatDateTime(dateTime) {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		},

		// 导出字典数据
		async handleExportDictData() {
			try {
				// 这里应该调用导出字典数据的API
				// 暂时使用模拟数据
				const exportData = this.tableData.map(item => ({
					字典类型: item.dictTypeName,
					字典标签: item.dictLabel,
					字典值: item.dictValue,
					排序: item.dictSort,
					样式属性: item.cssClass,
					表格回显样式: item.listClass,
					默认值: item.isDefault === 1 ? '是' : '否',
					状态: item.status === 1 ? '启用' : '停用',
					备注: item.remark,
					创建时间: this.formatDateTime(item.createdAt)
				}))

				// 转换为CSV格式
				const csvContent = this.convertToCSV(exportData)
				const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
				const url = URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = url
				link.download = `字典数据导出_${new Date().toLocaleDateString()}.csv`
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				URL.revokeObjectURL(url)

				this.$message.success('字典数据导出成功')
			} catch (error) {
				console.error('导出字典数据失败:', error)
				this.$message.error('导出失败')
			}
		},

		// 导入字典数据
		handleImportDictData() {
			this.importStep = 0
			this.importFile = null
			this.importPreviewData = []
			this.importDialogVisible = true
		},

		// 处理导入文件变化
		handleImportFileChange(file) {
			this.importFile = file.raw
			this.validateImportFile(file.raw)
		},

		// 验证导入文件
		validateImportFile(file) {
			const validTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel', 'application/json']
			const isValidType = validTypes.includes(file.type) || file.name.endsWith('.xlsx') || file.name.endsWith('.xls') || file.name.endsWith('.json')

			if (!isValidType) {
				this.$message.error('只支持Excel(.xlsx/.xls)和JSON格式文件')
				return false
			}

			const isLt10M = file.size / 1024 / 1024 < 10
			if (!isLt10M) {
				this.$message.error('文件大小不能超过10MB')
				return false
			}

			return true
		},

		// 下一步
		async handleNextStep() {
			if (this.importStep === 0) {
				if (!this.importFile) {
					this.$message.warning('请先选择文件')
					return
				}

				try {
					// 解析文件内容
					const data = await this.parseImportFile(this.importFile)
					this.importPreviewData = data
					this.importStep++
				} catch (error) {
					console.error('解析文件失败:', error)
					this.$message.error('文件解析失败，请检查文件格式')
				}
			} else if (this.importStep === 1) {
				this.importStep++
			}
		},

		// 解析导入文件
		async parseImportFile(file) {
			// 使用file参数进行文件解析
			console.log('解析文件:', file.name)
			// 这里应该调用文件解析API
			// 暂时使用模拟数据
			return [
				{
					dictTypeName: '用户性别',
					dictLabel: '男',
					dictValue: '1',
					dictSort: 1,
					cssClass: 'male',
					listClass: 'primary',
					isDefault: 1,
					status: 1,
					remark: '男性用户',
					importStatus: 'new'
				},
				{
					dictTypeName: '用户性别',
					dictLabel: '女',
					dictValue: '2',
					dictSort: 2,
					cssClass: 'female',
					listClass: 'danger',
					isDefault: 0,
					status: 1,
					remark: '女性用户',
					importStatus: 'new'
				}
			]
		},

		// 确认导入
		async handleConfirmImport() {
			this.importLoading = true
			try {
				// 这里应该调用导入字典数据的API
				// 模拟导入过程
				await new Promise(resolve => setTimeout(resolve, 2000))

				this.$message.success(`成功导入 ${this.getImportSummary().validCount} 条数据`)
				this.importDialogVisible = false
				this.loadData()
			} catch (error) {
				console.error('导入失败:', error)
				this.$message.error('导入失败')
			} finally {
				this.importLoading = false
			}
		},

		// 关闭导入对话框
		handleImportDialogClose() {
			this.importDialogVisible = false
			this.importStep = 0
			this.importFile = null
			this.importPreviewData = []
		},

		// 获取导入统计
		getImportSummary() {
			const newCount = this.importPreviewData.filter(item => item.importStatus === 'new').length
			const updateCount = this.importPreviewData.filter(item => item.importStatus === 'update').length
			const errorCount = this.importPreviewData.filter(item => item.importStatus === 'error').length
			const validCount = this.importPreviewData.filter(item => item.importStatus !== 'error').length

			return { newCount, updateCount, errorCount, validCount }
		},

		// 下载导入模板
		downloadTemplate() {
			const templateData = [
				{
					字典类型: 'user_gender',
					字典标签: '男',
					字典值: '1',
					排序: 1,
					样式属性: 'male',
					表格回显样式: 'primary',
					默认值: '是',
					状态: '启用',
					备注: '男性用户'
				},
				{
					字典类型: 'user_gender',
					字典标签: '女',
					字典值: '2',
					排序: 2,
					样式属性: 'female',
					表格回显样式: 'danger',
					默认值: '否',
					状态: '启用',
					备注: '女性用户'
				}
			]

			const csvContent = this.convertToCSV(templateData)
			const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
			const url = URL.createObjectURL(blob)
			const link = document.createElement('a')
			link.href = url
			link.download = '字典数据导入模板.csv'
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			URL.revokeObjectURL(url)

			this.$message.success('模板下载成功')
		},

		// 转换为CSV格式
		convertToCSV(data) {
			if (!data || data.length === 0) return ''

			const headers = Object.keys(data[0])
			const csvHeaders = headers.join(',')

			const csvRows = data.map(row => {
				return headers.map(header => {
					const value = row[header] || ''
					// 处理包含逗号或引号的值
					if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
						return `"${value.replace(/"/g, '""')}"`
					}
					return value
				}).join(',')
			})

			return [csvHeaders, ...csvRows].join('\n')
		}
	}
}
</script>

<style scoped>
/* 基础样式 */
* {
	font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
	background-color: #f0f2f5;
	color: #1a1a1a;
	margin: 0;
}

/* 容器布局 */
.app-container {
	max-width: 1440px;
	margin: 0 auto;
	display: grid;
	grid-template-columns: 240px 1fr;
	grid-template-rows: 64px 1fr;
	min-height: 100vh;
	background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
	grid-column: 1 / -1;
	background-color: #2C5AA0;
	display: flex;
	align-items: center;
	padding: 0 24px;
}

.logo {
	font-size: 18px;
	font-weight: bold;
	color: white;
	display: flex;
	align-items: center;
	gap: 8px;
}

.flex-grow {
	flex-grow: 1;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.gap-6 {
	gap: 24px;
}

.gap-2 {
	gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
	background-color: white;
	padding: 16px 0;
	border-right: 1px solid #e4e7ed;
}

.menu-item {
	padding: 12px 24px;
	color: #555;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.3s;
	cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
	background-color: #e8eff9;
	color: #2C5AA0;
	border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
	padding: 24px;
	display: grid;
	grid-template-rows: auto 1fr;
	gap: 24px;
	overflow-y: auto;
}

.main-content-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 16px;
	border-bottom: 1px solid #e4e7ed;
}

.header-actions {
	display: flex;
	gap: 12px;
}

/* 搜索区域 */
.search-bar {
	background: white;
	padding: 24px;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	margin-bottom: 24px;
}

/* 表格容器 */
.table-container {
	background: white;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	padding: 24px;
}

/* 分页容器 */
.pagination-container {
	margin-top: 20px;
	text-align: right;
}

/* 批量操作 */
.batch-operations {
	margin-top: 16px;
	padding: 12px;
	background-color: #f5f7fa;
	border-radius: 4px;
	display: flex;
	align-items: center;
	gap: 12px;
}

.batch-operations span {
	font-weight: 500;
	color: #606266;
}

/* 头像和退出登录 */
#img-head {
	height: 40px;
	width: 40px;
	border-radius: 50px;
}

.denglu {
	color: white;
	font-size: 15px;
	text-decoration: none;
}

.denglu:hover {
	color: #F44346;
}

.text-sm {
	font-size: 14px;
}

.text-white {
	color: white;
}

/* Element UI 样式调整 */
.el-table {
	margin-top: 16px;
}

.el-table th {
	background-color: #fafafa !important;
}

.el-form-item {
	margin-bottom: 0;
}

/* 字典导入样式 */
.import-tips {
	margin: 20px 0;
}

.template-download {
	text-align: center;
	margin-top: 10px;
}

.import-summary {
	margin-top: 20px;
}

/* 步骤条样式 */
.el-steps {
	margin-bottom: 30px;
}

/* 上传组件样式 */
.el-upload-dragger {
	width: 100%;
}

/* 结果组件样式 */
.el-result {
	padding: 20px 0;
}

/* 表格操作按钮组样式优化 */
.el-button-group .el-button {
	padding: 5px 10px;
	font-size: 12px;
}
</style>